package top.jybill.exceptionResover;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import top.jybill.domain.ResponseData;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyExceptionResover implements HandlerExceptionResolver {

  @Autowired
  private ResponseData res;
  /**
   * 异常处理
   * @param request
   * @param response
   * @param handler
   * @param ex
   * @return
   */
  public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    ModelAndView mv = new ModelAndView();
    // 自定义的异常
      res.metaPut("status", "500");
      if (ex.getMessage() == null) {
        res.metaPut("msg", ex.toString());
      } else {
        res.metaPut("msg", ex.getMessage());
      }

      // 响应
      try {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(new ObjectMapper().writeValueAsString(res));
      } catch (Exception e) {
        System.out.println(e.getMessage());
      }
    return mv;
  }
}
